package baseconfig

import (
	"gitee.com/ichub/goconfig/common/base/basedto"
	"gitee.com/ichub/goconfig/common/base/baseutils/goutils"
	"gitee.com/ichub/goconfig/common/base/baseutils/reflectutils"
	"gitee.com/ichub/goconfig/common/ichubconfig"
	"github.com/gogf/gf/v2/text/gstr"
	"github.com/gogf/gf/v2/util/gconv"
	"reflect"
	"strings"
)

type BaseConfig struct {
	basedto.BaseEntitySingle
}

func NewBaseConfig() *BaseConfig {
	var bc = &BaseConfig{}
	bc.InitProxy(bc)
	return bc
}
func (bc *BaseConfig) InjectConfigItem(some any) {

	var linkmap = reflectutils.ParseGocfgTag(some)

	for _, key := range linkmap.Keys() {
		value, found := linkmap.Get(key)
		if found {
			bc.ParseConfigItems(some, key.(string), value)
		}
	}
	if bc.Proxy() == nil {
		panic("some is nil!")
	}
	goutils.Info(some, "***")
}

/*
some is ptr
*/
func (bc *BaseConfig) ParseConfigItems(some any, key string, value any) {
	var svalue = strings.ReplaceAll(gconv.String(value), "${", "")
	svalue = strings.ReplaceAll(svalue, "}", "")

	var values = strings.Split(svalue, ":")
	var rv = ichubconfig.FindBeanIchubConfig().ReadVar(gstr.Trim(values[0]))
	var ifnil = rv == ""
	if ifnil && len(values) < 2 {
		return
	}
	if ifnil {
		rv = reflect.ValueOf(gstr.Trim(values[1]))
	}

	var rt = reflect.ValueOf(some).Elem()
	var fieldvalue = rt.FieldByName(key)
	bc.setConfigItem(fieldvalue, rv)
}
func (bc *BaseConfig) setConfigItem(fieldvalue reflect.Value, rv any) {
	switch fieldvalue.Kind() {
	case reflect.Int:
		fieldvalue.SetInt(gconv.Int64(rv))
	case reflect.Uint:
		fieldvalue.SetUint(gconv.Uint64(rv))
	case reflect.String:
		fieldvalue.SetString(gconv.String(rv))
	case reflect.Bool:
		fieldvalue.SetBool(gconv.Bool(rv))
	case reflect.Float64:
		fieldvalue.SetFloat(gconv.Float64(rv))
	case reflect.Float32:
		fieldvalue.SetFloat(gconv.Float64(rv))

	}

}
